$(document).ready(function () {

	//Tab in textarea.code
	$('textarea.code').keydown(function (e) {
		if (e.keyCode == 9) {
			var myValue = "\t";
			var startPos = this.selectionStart;
			var endPos = this.selectionEnd;
			var scrollTop = this.scrollTop;

			this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos,this.value.length);
			this.focus();
			this.selectionStart = startPos + myValue.length;
			this.selectionEnd = startPos + myValue.length;
			this.scrollTop = scrollTop;

			e.preventDefault();
		}
	});

	//Cmd+S -> save
	$(document).keydown(function (e) {
		var $form = $('form.edit');

		if (!$form.length) {
			return true;
		}

		if (e.keyCode == 83 && (e.metaKey || e.ctrlKey)) {
			var $submit = $form.find(':submit').eq(0).click();

			$($form).append('<input>', {
				type: 'hidden',
				name: $submit.attr('name'),
				value: $submit.attr('value')
			});

			$form.submit()
			
			return false;
		}
	});

	//Preview html code
	$('.preview').click(function () {
		var html = $('#' + $(this).attr('rel')).val();
		$.colorbox({
			html: '<div class="text">' + html + '</div>',
			title: $(this).text(),
			opacity: 0.2,
			maxWidth: '90%',
			maxHeight: '90%'
		});
	});
});